var express = require('express');
var glob = require('glob');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var compress = require('compression');
var methodOverride = require('method-override');
var swig = require('swig-templates');
var basicAuth = require("basic-auth");
var common = require('../app/controllers/base/common.js');
swig.setFilter('dump', function (input) {
    console.log('\n\r')
    console.log(input.length)
    return console.log(input);
});
swig.setDefaults({ cache: 'memory' });
var auth = function (req, resp, next) {
    function unauthorized(res) {
        res.set('WWW-Authenticate', 'Basic realm=Authorization Required');
        return resp.sendStatus(401);
    }

    var user = basicAuth(req);

    if (!user || !user.name || !user.pass) {
        return unauthorized(resp);
    }

    if (user.name === 'leisutiyu' && user.pass === 'leisutiyu666') {
        return next();
    } else {
        return unauthorized(resp);
    }
};

module.exports = function(app, config) {
    var env = process.env.NODE_ENV || 'development';
    app.locals.ENV = env;
    app.locals.ENV_DEVELOPMENT = env == 'development';

    app.engine('html', swig.renderFile);
    if(env == 'development'){
        app.set('view cache', false);
        swig.setDefaults({ cache: false });
    }
    app.set('views', config.root + '/pages/views');
    app.set('view engine', 'html');

    // app.use(favicon(config.root + '/public/img/favicon.ico'));
    app.use(logger('dev'));
    app.use(bodyParser.json());
    app.use(bodyParser.urlencoded({
        extended: true
    }));
    app.use(cookieParser());
    app.use(compress());
    app.use(express.static(config.root + '/public'));
    app.use(methodOverride());

    // app.get('*', auth, function (req, resp, next) {
    //   next()
    // });

    var controllers = glob.sync(config.root + '/app/controllers/*.js');
    controllers.forEach(function (controller) {
        require(controller)(app);
    });

    app.use(function (req, res, next) {
        var err = new Error('Error Page');
        err.status = 404;
        next(err);
    });

    //basic auth
    app.get('*', auth, function (req, resp, next) {
        next()
    });

    if(app.get('env') === 'development'){
        app.use(function (err, req, res, next) {
            res.status(err.status || 500);
            res.render(err.status==404?'error/404':'error/500', {
                message: err.message,
                error: err,
                title: '错误'
            });
            // res.write(err)
        });
    }else{
        app.use(function (err, req, res, next) {
            res.status(err.status || 500);
            res.render(err.status==404?'error/404':'error/500', {
                message: err.message,
                error: {},
                title: '错误'
            });
            // res.write(err)
        });
    }
};
